package cn.itcast.goods.order.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Properties;

import cn.itcast.commons.CommonUtils;
import cn.itcast.goods.cart.domain.CartItem;
import cn.itcast.goods.cart.service.CartItemService;
import cn.itcast.goods.order.domain.Order;
import cn.itcast.goods.order.domain.OrderItem;
import cn.itcast.goods.order.service.OrderService;
import cn.itcast.goods.pager.PageBean;
import cn.itcast.goods.user.domain.User;
import cn.itcast.servlet.BaseServlet;

public class OrderServlet extends BaseServlet {

	private CartItemService cartItemService = new CartItemService();
	private OrderService orderService = new OrderService();

	/**
	 * 创建订单条目
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public String create(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		//1.获取参数（购物车中所有的id以及收获地址）
		String  cartItemIds = request.getParameter("cartItemIds");
		String address = request.getParameter("address");
		//2.通过cartItemService 加载购物车中的所有条目
		List<CartItem> cartItemList =cartItemService.loadCartItems(cartItemIds);
		//3.创建订单
		Order order = new Order();
		order.setOid(CommonUtils.uuid());
		order.setOrdertime(String.format("%tF %<tT", new Date()));
		BigDecimal total = new BigDecimal("0");
		for(CartItem cartItem:cartItemList){
			total = total.add(new BigDecimal(Double.toString(cartItem.getSubtotal())));
		}
		order.setTotal(total.doubleValue()); //把bigDecimal类型的转换成double类型的
		order.setStatus(1);//设置状态，刚生成的订单状态为1，表示未支付
		order.setAddress(address);
		User owner = (User) request.getSession().getAttribute("sessionUser");
		order.setOwner(owner);
		//4. 通过List<CartItem>来创建List<OrderItem>，再把List<OrderItem>设置给Order
		List<OrderItem> orderItemList = new ArrayList<OrderItem>();
		for(CartItem cartItem :cartItemList){
			OrderItem orderItem = new OrderItem();
			orderItem.setOrderItemId(CommonUtils.uuid());
			orderItem.setQuantity(cartItem.getQuantity());
			orderItem.setSubtotal(cartItem.getSubtotal());
			orderItem.setBook(cartItem.getBook());
			orderItem.setOrder(order);
			
			orderItemList.add(orderItem);
		}
		order.setOrderItemList(orderItemList);
		//5. 调用orderService方法生成order
		orderService.create(order);
		//删除购物车中用来生成订单的条目
		cartItemService.deleteBatch(cartItemIds);
		//6. 保存Order到request中，转发到/jsps/order/ordersucc.jsp
		request.setAttribute("order", order);
		return "/jsps/order/ordersucc.jsp";
		

	}
	/**
	 * 获取当前的页码
	 * @param request
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	private int getPageCode(HttpServletRequest request) throws ServletException, IOException{
		
		String pageCode = request.getParameter("pc");
		if(pageCode == null){
			return 1;
		}
		try{
			return Integer.parseInt(pageCode);
		}catch(Exception e){
			return 1;
		}
		
		
	}
    /**
     * 获取请求的url,但是出去pc参数
     * @param request
     * @return
     * @throws ServletException
     * @throws IOException
     */
	public String getUrl(HttpServletRequest request)
			throws ServletException, IOException {
	     String url = request.getRequestURI()+"?"+request.getQueryString();
	     int fromIndex = url.lastIndexOf("&pc=");
	     if(fromIndex == -1){
	    	 return url;
	     }
	     int toIndex = url.indexOf("&",fromIndex+1);
	     if(toIndex == -1){
	    	 return url.substring(0, fromIndex);
	     }
	     return url.substring(0, fromIndex)+url.substring(toIndex);
	}
	
	/**
	 * 我的订单
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String myOrders(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		//1.获取当前的页码
		int pc= getPageCode(request);
		//2.获取当前的用户uid
		User user = (User) request.getSession().getAttribute("sessionUser");
		PageBean<Order> pb =orderService.myOrders(user.getUid(),pc);
		
		//3.获取url,设置给pageBean
		String url = getUrl(request);
		pb.setUrl(url);
		//4.将PageBean保存到request中，并且转发到"/jsps/order/list.jsp"
		request.setAttribute("pb", pb);
		return "/jsps/order/list.jsp";

	}
	
	/**
	 * 加载订单的数据
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String load(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String oid = request.getParameter("oid"); //获取订单编号
		String oper = request.getParameter("oper");// 获取操作，包括查看，确认，交易，收货
		//加载订单并保存到request中
		request.setAttribute("order", orderService.load(oid));
		//把操作也保存到request中
		request.setAttribute("oper", oper);
		//转发到desc.jsp
		return "/jsps/order/desc.jsp";
	}
	
	/**
	 * 取消订单
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String cancel(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//获取订单的oid
		String oid = request.getParameter("oid");
		orderService.updateStatus(oid,5);
		//把订单已取消放到request中，并且转发到"/jsps/msg.jsp"
		
		request.setAttribute("code", "success");
		request.setAttribute("msg", "订单取消成功！");
		return "/jsps/msg.jsp";
	}
	/**
	 * 确认收货
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String confirm(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//获取订单的oid
		String oid = request.getParameter("oid");
		orderService.updateStatus(oid, 4);
		request.setAttribute("code", "success");
		request.setAttribute("msg", "收货成功！");
		return "/jsps/msg.jsp";
	}
	
	/**
	 * 获取oid.加载订单，然后转发到pay.jsp
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String prepareForPayment(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//获取oid
		String oid = request.getParameter("oid");
		//加载订单
		request.setAttribute("order", orderService.load(oid));
		return "/jsps/order/pay.jsp";
		
	}
    /**
     * 支付接口
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
	public String payment(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//准备访问易宝网关的数据
		Properties props = new Properties();
		props.load(this.getClass().getClassLoader().getResourceAsStream("payment.properties"));
		String p0_Cmd = "Buy"; //业务类型
		String p1_Merld = props.getProperty("p1_MerId"); //商户编号
		String p2_Order = request.getParameter("oid"); //商户订单号
		String p3_Amt = "0.01"; //支付金额
		String p4_Cur = "CNY"; //交易币种
		String p5_Pid = ""; //商品名称
		String p6_Pact = ""; //商品种类
		String p7_Pdesc = ""; //商品描述
		String p8_Url = props.getProperty("p8_Url"); //商户接受支付成功的数据的地址
		String p9_SAF = ""; //送货地址
		String pa_MP = ""; //商户扩展信息
		String pd_FrId = props.getProperty("yh"); //支付通道编码
		String pr_NeedResponse = "1"; // 应答机制
		// 使用密钥生成hmac，它是不可逆的
		String keyValue = props.getProperty("keyValue");
		String hmac = PaymentUtil.buildHmac(p0_Cmd,p1_Merld,p2_Order,p3_Amt,p4_Cur,p5_Pid,p6_Pact,
				p7_Pdesc,p8_Url,p9_SAF,pa_MP,pd_FrId,pr_NeedResponse,keyValue); //签名数据
		
		
		//把数据保存到request中，转发到/WEB-INF/jsp/sendpay.jsp页面，这个页面会把数据显示在表单中，表单会自动提交到易宝网
		request.setAttribute("p0_Cmd",p0_Cmd);
		request.setAttribute("p1_Merld",p1_Merld);
		request.setAttribute("p2_Order",p2_Order);
		request.setAttribute("p3_Amt",p3_Amt);
		request.setAttribute("p4_Cur",p4_Cur);
		request.setAttribute("p5_Pid",p5_Pid);
		request.setAttribute("p6_Pact",p6_Pact);
		request.setAttribute("p7_Pdesc",p7_Pdesc);
		request.setAttribute("p8_Url",p8_Url);
		request.setAttribute("p9_SAF",p9_SAF);
		request.setAttribute("pa_MP",pa_MP);
		request.setAttribute("pd_FrId",pd_FrId);
		request.setAttribute("pr_NeedResponse",pr_NeedResponse);
		request.setAttribute("hmac",hmac);
		
		return "/WEB-INF/jsp/sendpay.jsp";
	}
	
	/**
	 * 回调函数
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String back(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String p1_MerId = request.getParameter("p1_MerId");//商户编号
		String r0_Cmd = request.getParameter("r0_Cmd");// 业务类型
		String r1_Code = request.getParameter("r1_Code");//支付结果
		String r2_TrxId = request.getParameter("r2_TrxId");//易宝支付交易流水号
		String r3_Amt = request.getParameter("r3_Amt");//支付金额
		String r4_Cur = request.getParameter("r4_Cur");//交易币种
		String r5_Pid = request.getParameter("r5_Pid");// 商品名称
		String r6_Order = request.getParameter("r6_Order");//商户订单号
		String r7_Uid = request.getParameter("r7_Uid");//易宝支付会员ID
		String r8_MP = request.getParameter("r8_MP");//商户扩展信息
		String r9_BType = request.getParameter("r9_BType");//交易结果返回类型
		String hmac = request.getParameter("hmac");//签名数据

		//校验签名是否有效
		Properties props = new Properties();
		props.load(this.getClass().getClassLoader().getResourceAsStream("payment,properties"));
		String keyValue = props.getProperty("keyValue"); //获取密钥，从配置文件上加载
		boolean flag = PaymentUtil.verifyCallback(hmac, p1_MerId, r0_Cmd, r1_Code, r2_TrxId, r3_Amt, r4_Cur, r5_Pid, r6_Order, r7_Uid, r8_MP, r9_BType, keyValue);
		if(flag)
		{
			if("1".equals(r1_Code))
			{
				int status = orderService.findStatusByOrder(r6_Order);//修改订单状态为已支付
				if(status == 1) //如果订单状态为未支付，修改订单状态
				{
					orderService.updateStatus(r6_Order, 2);
				}
				if("1".equals(r9_BType))//重定向访问本方法
				{
					request.setAttribute("code", "success");
					request.setAttribute("msg", "支付成功！");
				}
				else if("2".equals(r9_BType))//点对点访问本方法，回写success
				{
					response.getWriter().write("success");
					return null;
				}
			}
			else
			{
				request.setAttribute("code", "error");
				request.setAttribute("msg", "支付失败！");
			}
		}
		else
		{
			System.out.println("无效的签名！");
			request.setAttribute("code", "error");
			request.setAttribute("msg", "无效的卡名！");
		}	
		return "/jsps/msg.jsp";
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	}


}
